package cn.bb.bbstudy.controller;

import cn.bb.bbstudy.pojo.Comment;
import cn.bb.bbstudy.pojo.Question;
import cn.bb.bbstudy.pojo.QuestionCategory;
import cn.bb.bbstudy.pojo.User;
import cn.bb.bbstudy.service.*;
import cn.bb.bbstudy.utils.BBUtils;
import cn.bb.bbstudy.vo.BlogWriteForm;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Controller
public class QuestionController {
    @Autowired
    QuestionCategoryService questionCategoryService;
    @Autowired
    QuestionService questionService;
    @Autowired
    CommentService commentService;
    @Autowired
    UserService userService;
    @Autowired
    FileUploadService fileUploadService;

    // 编辑一个新的问题 这是展示页
    @GetMapping("/question/write")
    public String toWrite(Model model) {
        //查询所有问题的标签 放入
        List<QuestionCategory> categoryList = questionCategoryService.selectAll();
        model.addAttribute("categoryList", categoryList);
        return "question/write";
    }

    /**
     * 问题列表展示请求
     */
    @GetMapping("/question")
    public String lists(Model model, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit) {
        //默认一页显示10条数据 根据更新的时间来定
        PageHelper.startPage(page, limit);
        PageInfo<Question> info = new PageInfo<>(questionService.findAllDesc());
        model.addAttribute("info", info);
        List<QuestionCategory> categories = questionCategoryService.selectAll();
        model.addAttribute("categoryList", categories);
        return "question/list";
    }

    @GetMapping("/question/read/{qid}")
    public String read(Model model, @PathVariable("qid") String qid) {
        Question question = questionService.findOneByQid(qid);
        //每刷新一次 浏览量+1
        question.setViews(question.getViews() + 1);
        questionService.updateByPrimaryKeySelective(question);
        model.addAttribute("question", question);
        //评论里的topic_id 对应的就是问题对象里的qid
        List<Comment> comments = commentService.selectAllByTopic(qid);
        model.addAttribute("comments", comments);
        return "question/read";
    }

    /**
     * 保存问题
     *
     * @param questionWriteForm
     * @return
     */
    @PostMapping("/question/write")
    public String save(BlogWriteForm questionWriteForm) {
        //接受问题表单vo
        Question question = new Question();
        String qid = BBUtils.getUuid();
        question.setQid(qid);
        question.setTitle(questionWriteForm.getTitle());
        question.setContent(questionWriteForm.getContent());
        question.setStatus(0);
        question.setSort(0);
        question.setViews(0);
        //设置用户相关
        question.setAuthorId(questionWriteForm.getAuthorId());
        question.setAuthorAvatar(questionWriteForm.getAuthorAvatar());
        question.setAuthorName(questionWriteForm.getAuthorName());
        //设置栏目相关
        QuestionCategory category = questionCategoryService.selectByPrimaryKey(questionWriteForm.getCategoryId());
        question.setCategoryId(category.getId());
        question.setCategoryName(category.getCategory());
        question.setGmtCreate(BBUtils.getTime());
        question.setGmtUpdate(BBUtils.getTime());
        questionService.insertSelective(question);

        return "redirect:/question/read/" + qid;

    }

    /**
     * 更新问题
     * @param question
     * @return
     */
    @PostMapping("/question/edit")
    public String update(Question question) {
        String qid = question.getQid();
        Question queryQuestion = questionService.findOneByQid(qid);
        queryQuestion.setTitle(question.getTitle());
        queryQuestion.setContent(question.getContent());
        queryQuestion.setCategoryId(question.getCategoryId());
        queryQuestion.setGmtUpdate(BBUtils.getTime());
        questionService.updateByPrimaryKeySelective(queryQuestion);
        return "redirect:/question/read/" + qid;
    }

    /**
     * 删除问题
     */
    @GetMapping("question/delete/{uid}/{qid}")
    public String delete(@PathVariable("uid") String uid,@PathVariable("qid") String qid) {
        //删除两张表的数据 问题表  评论表对应的都要删掉 评论就别删了 太麻烦了
        Question question = questionService.findOneByQid(qid);
        User user = userService.findUserByUid(uid);
        BBUtils.print(user);
        if (question.getAuthorId().equals(uid) || user.getRoleId() == 1) {
            questionService.deleteByPrimaryKey(question.getId());
            BBUtils.print("删除成功");
            return "redirect:/question";
        } else {
            return "error/404";
        }

    }
    /**
     * 编辑问题
     */
    @GetMapping("question/edit/{uid}/{qid}")
    public String edit(Model model,@PathVariable("uid") String uid,@PathVariable("qid") String qid) {
        //根据qid 得到question对象 进行回显 同时标签集合也要传到前端
        //只有该用户或者管理员可以进行修改
        User user = userService.findUserByUid(uid);
        Question question = questionService.findOneByQid(qid);
        BBUtils.print(user);
        if (question.getAuthorId().equals(uid) || user.getRoleId() == 1) {
            model.addAttribute("question", question);
            //查询所有标签
            List<QuestionCategory> categories = questionCategoryService.selectAll();
            model.addAttribute("categoryList", categories);
            return "question/edit";
        } else {
            BBUtils.print("非法编辑");
            return "error/404";
        }
    }

    /**
     *  发表评论 直接状态置为解决....
     * @param qid
     * @param comment
     * @return
     */
    @PostMapping("/question/comment/{qid}")
    public String comment(@PathVariable("qid") String qid, Comment comment) {
        BBUtils.print(comment);
        comment.setCommentId(BBUtils.getUuid());
        //1为博客 2为问题
        comment.setTopicCategory(2);
        comment.setGmtCreate(BBUtils.getTime());
        commentService.insertSelective(comment);
        Question question = questionService.findOneByQid(qid);
        question.setStatus(1);
        questionService.updateByPrimaryKeySelective(question);
        //重定向到问题详情页
        return "redirect:/question/read/" + qid;
    }



    /**
     * 编辑器图片上传
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/question/write/file/upload")
    @ResponseBody
    //editormd-image-file不可更改
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        String upload = fileUploadService.upload(file);
        //给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url", upload);
        res.put("success", 1);
        res.put("message", "upload success!");
        BBUtils.print(res.toJSONString());

        return res;
    }
}
